package com.edu.hre.struts.action.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.navigator.menu.MenuComponent;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.cache.PassiveDynaCache;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.CustomRequestProcessor;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.common.utils.StringTool;
import com.edu.hre.db.pojo.HreUserRole;
import com.edu.hre.db.pojo.HreUserRoleScreen;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.admin.RoleGroupForm;

public class RoleGroupAction extends DispatchAction {
	
	private static final Logger logger = Logger.getLogger(RoleGroupAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private static final PassiveDynaCache passiveDynaCache = BeanFinder.getBean(PassiveDynaCache.BEAN_NAME, PassiveDynaCache.class);
	private final String ACTION_NAME = "roleGroup";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		RoleGroupForm beanForm = (RoleGroupForm) form;
		MenuComponent[] menuComponent = CustomRequestProcessor.menuComponent;
		
		if(request.getParameter(StringConstants.BTN_ADD) != null){
			if(StringUtils.isBlank(beanForm.getRoleGroupName())){
				beanForm.setMessage("Role group name can not be blank!");
				return mapping.findForward(ACTION_NAME);
			} else {
				beanForm.setMessage("");
			}
			HreUserRole userRole = new HreUserRole();
			userRole.setDisplayName(beanForm.getRoleGroupName());
			userRole.setIsAssignable(true);
			userRole.setIsPredefined(true);
			userRole.setName(StringTool.unicode2KoDau(beanForm.getRoleGroupName().replace(" ", "")));
			baseService.saveOrUpdate(userRole);
			createRoleScreen(request, menuComponent, userRole.getId());
			beanForm.setSelectedUserRoles(userRole.getId());
		} else if(request.getParameter(StringConstants.BTN_EDIT) != null){
			if(StringUtils.isBlank(beanForm.getRoleGroupName())){
				beanForm.setMessage("Role group name can not be blank!");
				return mapping.findForward(ACTION_NAME);
			} else {
				beanForm.setMessage("");
			}
			HreUserRole userRole = baseService.getPojo(beanForm.getSelectedUserRoles(), HreUserRole.class);
			userRole.setDisplayName(beanForm.getRoleGroupName());
			userRole.setIsAssignable(true);
			userRole.setIsPredefined(true);
			userRole.setName(StringTool.unicode2KoDau(beanForm.getRoleGroupName().replace(" ", "")));
			baseService.saveOrUpdate(userRole);
			createRoleScreen(request, menuComponent, userRole.getId());
			beanForm.setSelectedUserRoles(userRole.getId());
			
			String key = RequestUtils.Attribute.MENU_ROLES + userRole.getId();
			passiveDynaCache.removeCachedItem(key);
		}
		List<HreUserRole> listUserRoles = baseService.getPojosAnd(new String[]{"isAssignable", "name"}, new int[]{Compare.EQUAL, Compare.NOT_EQUAL}, new Object[]{true, "Admin"}, null, null, 0, 0, HreUserRole.class);
		HreUserRole hreUserRole = new HreUserRole();
		hreUserRole.setDisplayName("New role group");
		hreUserRole.setId(0);
		listUserRoles.add(0, hreUserRole);
		
		HreUserRole userRole = baseService.getPojo(beanForm.getSelectedUserRoles(), HreUserRole.class);
		if(userRole != null){
			beanForm.setRoleGroupName(userRole.getDisplayName());
		}
		List<HreUserRoleScreen> listUserRoleScreen = baseService.getPojos("userRoleId", Compare.EQUAL, beanForm.getSelectedUserRoles(), null, null, 1000, 0, HreUserRoleScreen.class);
		StringBuilder html = new StringBuilder();
		buildHtml(menuComponent, html, listUserRoleScreen);
		String htmlTree = html.toString().replaceFirst("<ul", "<ul id=\"red\" class=\"treeview-red\"");
		beanForm.setListUserRoles(listUserRoles);
		beanForm.setHtmlTree(htmlTree);
		return mapping.findForward(ACTION_NAME);
	}
	
	private void createRoleScreen(HttpServletRequest request, MenuComponent[] menuComponent, int userRoleId){
		if(menuComponent == null || menuComponent.length == 0){
			return;
		} 
		for(int i = 0; i < menuComponent.length; i++){
			if(StringUtils.isNotBlank(menuComponent[i].getPage()) && !"#".equals(menuComponent[i].getPage())){
				String actionName = normalizeActionName(menuComponent[i].getPage());
				HreUserRoleScreen userRoleScreen = baseService.getFirstPojoAnd(new String[]{"userRoleId", "actionName"}, new int[]{Compare.EQUAL, Compare.EQUAL}, new Object[]{userRoleId, actionName}, null, null, 0, HreUserRoleScreen.class);
				if(userRoleScreen == null){
					userRoleScreen = new HreUserRoleScreen();
				}
				if(request.getParameter("v_" + actionName) != null){
					userRoleScreen.setCanRead(true);
				} else {
					userRoleScreen.setCanRead(false);
				}
				if(request.getParameter("a_" + actionName) != null){
					userRoleScreen.setCanCreate(true);
				} else {
					userRoleScreen.setCanCreate(false);
				}
				if(request.getParameter("e_" + actionName) != null){
					userRoleScreen.setCanUpdate(true);
				} else {
					userRoleScreen.setCanUpdate(false);
				}
				if(request.getParameter("d_" + actionName) != null){
					userRoleScreen.setCanDelete(true);
				} else {
					userRoleScreen.setCanDelete(false);
				}
				userRoleScreen.setUserRoleId(userRoleId);
				userRoleScreen.setActionName(actionName);
				baseService.saveOrUpdate(userRoleScreen);
			}
			MenuComponent[] childs = menuComponent[i].getMenuComponents();
			createRoleScreen(request, childs, userRoleId);
		}
	}
	
	private void buildHtml(MenuComponent[] menuComponent, StringBuilder html, List<HreUserRoleScreen> listUserRoleScreen){
		if(menuComponent == null || menuComponent.length == 0){
			return;
		} 
		html.append("\n<ul>");
		for(int i = 0; i < menuComponent.length; i++){
			if("hidden_role".equalsIgnoreCase(menuComponent[i].getAlign())){
				continue;
			}
			if("#".equals(menuComponent[i].getRoles()) || "#".equals(menuComponent[i].getModule())){
				 continue;
			}
			MenuComponent[] childs = menuComponent[i].getMenuComponents(); 
			html.append("\n<li style=\"width: 500px; font-size: 15px;font-weight:bold;\" title=\"" + (menuComponent[i].getToolTip() == null? "" : menuComponent[i].getToolTip())  + "\">"); 
			html.append(menuComponent[i].getTitle());
			String checkedCreate = "";
			String checkedUpdate = "";
			String checkedDelete = "";
			String checkedRead = "";
			if(StringUtils.isNotBlank(menuComponent[i].getPage()) && !"#".equals(menuComponent[i].getPage())){
				HreUserRoleScreen userRoleScreen = getRolesScreenByActionName(listUserRoleScreen, normalizeActionName(menuComponent[i].getPage()));
				if(userRoleScreen != null){
					if(userRoleScreen.isCanCreate()){
						checkedCreate = "checked";
					}
					if(userRoleScreen.isCanDelete()){
						checkedDelete = "checked";
					}
					if(userRoleScreen.isCanUpdate()){
						checkedUpdate = "checked";
					}
					if(userRoleScreen.isCanRead()){
						checkedRead = "checked";
					}
				}
			}
			String isTailElement = "";
			if((childs == null || childs.length == 0) && i == menuComponent.length - 1){
				isTailElement = "ite=\"t\" ";
			}
			if(StringUtils.isBlank(menuComponent[i].getDescription())){
				html.append("\n<input " + isTailElement + checkedDelete + " style=\"float:right;\" name=\"d_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:blue;font-weight:normal;\">Delete</a></input>");
				html.append("\n<input " + isTailElement + checkedUpdate + " style=\"float:right;\" name=\"e_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:blue;font-weight:normal;\">Edit</a></input>");
				html.append("\n<input " + isTailElement + checkedCreate + " style=\"float:right;\" name=\"a_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:blue;font-weight:normal;\">Add</a></input>");
				html.append("\n<input " + isTailElement + checkedRead   + " style=\"float:right;\" name=\"v_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:blue;font-weight:normal;\">View</a></input>");
			} else {
				if(menuComponent[i].getDescription().contains("d")){
					html.append("\n<input " + isTailElement + checkedDelete + " style=\"float:right;\" name=\"d_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:blue;font-weight:normal;\">Delete</a></input>");
				} else {
					html.append("\n<input hidden=\"true\" " + isTailElement + checkedDelete + " style=\"float:right;\" name=\"d_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:#DEDEDD;font-weight:normal;\">Delete &nbsp;&nbsp;&nbsp;&nbsp;</a></input>");
				}
				if(menuComponent[i].getDescription().contains("e")){
					html.append("\n<input " + isTailElement + checkedUpdate + " style=\"float:right;\" name=\"e_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:blue;font-weight:normal;\">Edit</a></input>");
				} else {
					html.append("\n<input hidden=\"true\" " + isTailElement + checkedUpdate + " style=\"float:right;\" name=\"e_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:#DEDEDD;font-weight:normal;\">Edit &nbsp;&nbsp;&nbsp;&nbsp;</a></input>");
				}
				if(menuComponent[i].getDescription().contains("a")){
					html.append("\n<input " + isTailElement + checkedCreate + " style=\"float:right;\" name=\"a_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:blue;font-weight:normal;\">Add</a></input>");
				} else {
					html.append("\n<input hidden=\"true\" " + isTailElement + checkedCreate + " style=\"float:right;\" name=\"a_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:#DEDEDD;font-weight:normal;\">Add &nbsp;&nbsp;&nbsp;&nbsp;</a></input>");
				}
				if(menuComponent[i].getDescription().contains("v")){
					html.append("\n<input " + isTailElement + checkedRead   + " style=\"float:right;\" name=\"v_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:blue;font-weight:normal;\">View</a></input>");
				} else {
					html.append("\n<input hidden=\"true\" " + isTailElement + checkedRead   + " style=\"float:right;\" name=\"v_" + normalizeActionName(menuComponent[i].getPage()) + "\" onclick=\"rolesProcess(this);\" type=\"checkbox\"><a style=\"margin-left: 10px;float:right;font-size: 13px;color:#DEDEDD;font-weight:normal;\">View &nbsp;&nbsp;&nbsp;&nbsp;</a></input>");
				}
			}
			buildHtml(childs, html, listUserRoleScreen);
			html.append("\n</li>");
		}
		html.append("\n</ul>");
	}
	
	private HreUserRoleScreen getRolesScreenByActionName(List<HreUserRoleScreen> listUserRoleScreen, String actionName){
		for(int i = 0; listUserRoleScreen != null && i < listUserRoleScreen.size(); i++){
			if(actionName != null && actionName.equals(listUserRoleScreen.get(i).getActionName())){
				return listUserRoleScreen.get(i);
			}
		}
		return null;
	}
	
	public static String normalizeActionName(String actionName){
		try {
			actionName = actionName.replace(".do", "").replace("/", "");
			if(actionName.contains("?")){
				actionName = actionName.substring(0, actionName.indexOf("?"));
			}
			return actionName;
		} catch (Exception e) {
			return actionName;
		}
	}
}
